package com.googlecode.wickedforms.xvergabe.modelers.components;

import java.util.Locale;

import org.apache.xmlbeans.XmlObject;
import org.xvergabe.xsd.forms.components.x20.AbstractComponent;
import org.xvergabe.xsd.forms.components.x20.AbstractField;
import org.xvergabe.xsd.forms.components.x20.OrSection;
import org.xvergabe.xsd.forms.components.x20.RoleType;

import com.googlecode.wickedforms.model.OrSectionModel;
import com.googlecode.wickedforms.xvergabe.modelers.FormModeller;
import com.googlecode.wickedforms.xvergabe.modelers.XmlModeller;
import com.googlecode.wickedforms.xvergabe.modelers.fields.AbstractFieldModeller;
import com.googlecode.wickedforms.xvergabe.modelers.fields.BooleanFieldModeller;
import com.googlecode.wickedforms.xvergabe.types.ComponentType;
import com.googlecode.wickedforms.xvergabe.util.XMLBeansUtil;

public class OrSectionModeller implements XmlModeller<OrSection, OrSectionModel> {
//TODO ursprünglich kopiert von XorSectionModeller. Arbeitsweise u.U. noch anzupassen. 04.07.2013 
	AbstractComponentModeller abstractComponentModeller;
	AbstractFieldModeller abstractFieldModeller;
	BooleanFieldModeller booleanFieldModeller;
	private final FormModeller formModeller;
	
	public OrSectionModeller(FormModeller formModeller){
		this.formModeller = formModeller;
	}
	
	@Override
	public OrSectionModel createModelFromXml(final OrSection xmlObject, final Locale locale, final RoleType.Enum sellerMode) {

		abstractComponentModeller = new AbstractComponentModeller(formModeller);
		
		abstractFieldModeller = new AbstractFieldModeller();

		booleanFieldModeller = new BooleanFieldModeller();
		
		OrSectionModel section = new OrSectionModel(ComponentType.ORSECTION.getMessage(locale));

		if (xmlObject.getMetadata() != null) {
			section.setLabel(XMLBeansUtil.getLabel(xmlObject.getMetadata(), locale));
		}

		for (XmlObject sectionElement : xmlObject.selectPath("./*")) {

			section.add(booleanFieldModeller.createModelFromXml(org.xvergabe.xsd.forms.components.x20.Boolean.Factory.newInstance(), locale, sellerMode));
			
			if (sectionElement instanceof AbstractField) {
				AbstractField component = (AbstractField) sectionElement;
				section.add(abstractFieldModeller.createModelFromXml(component, locale, sellerMode));
			}else if (sectionElement instanceof AbstractComponent) {
					AbstractComponent component = (AbstractComponent) sectionElement;
					section.add(abstractComponentModeller.createModelFromXml(component, locale, sellerMode));
			}else {
				throw new RuntimeException("Unknown component! Cannot create model for xml component of type " + xmlObject.getClass());
			}
		}
		
		return section;
	}
}
